package com.gxjtkyy.datadistributer.writer.rdbms.util;

import com.gxjtkyy.datadistributer.writer.rdbms.config.WriterConfig;
import com.gxjtkyy.datadistributer.writer.rdbms.vo.TableColumns;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: tanhaichao
 * @create: 2024/10/23 16:21
 **/
@Slf4j
@Component
@AllArgsConstructor
public class TableColumnsUtil {
    private final JdbcTemplate jdbcTemplate;
    private final WriterConfig writerConfig;

    public Map<String, Map<String, String>> columnNameMap = new HashMap<>();

    @PostConstruct
    public void init(){
        log.info("***************开始将入库表字段写入缓存**********************");
        this.writerConfig.getListenTopics().forEach((topic, value) ->{
//            List<String> columnNameList = jdbcTemplate.queryForList("SELECT column_name FROM information_schema.columns WHERE table_name = ?", String.class, topic);
            List<TableColumns> columnNameList = jdbcTemplate.query("SELECT column_name as columnName,udt_name as udtName FROM information_schema.columns WHERE table_name = ?",
                    BeanPropertyRowMapper.newInstance(TableColumns.class), topic);
            columnNameList.forEach(columnName -> columnNameMap.computeIfAbsent(topic, k -> new HashMap<>()).put(columnName.getColumnName(), columnName.getUdtName()));
        });
        log.info("***************结束将入库表字段写入缓存**********************");
    }
}
